package admin

import (
	"github.com/gin-gonic/gin"
	"mojieshi/define"
	"mojieshi/models"
	"net/http"
	"strconv"
	"time"
)

// 获取文章分类
func ArticleCategoryList(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonData, "")
		return
	}
	var list []models.MArticleCategory
	var count int64
	err = models.DB.Model(new(models.MArticleCategory)).Where("aid=?", jsonData.Aid).Count(&count).Order("sort ASC,id").Find(&list).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10001,
			"msg":  err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data": map[string]interface{}{
			"list":  list,
			"count": count,
		},
	})
}

// 新增/修改文章分类
func ArticleCateGoryAdd(c *gin.Context) {
	//获取传值
	var jsonData models.MArticleCategory
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	if jsonData.ID > 0 {
		//修改数据
		var editData = map[string]interface{}{
			"name":     jsonData.Name,
			"pic":      jsonData.Pic,
			"status":   jsonData.Status,
			"pid":      jsonData.Pid,
			"sub_name": jsonData.SubName,
		}
		err = models.DB.Model(new(models.MArticleCategory)).Where("id=?", jsonData.ID).Updates(&editData).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 10003,
				"msg":  err.Error(),
			})
			return
		}
		//写入日志
		userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
		userName, bid := models.UserName(userId)
		logData := "管理员：" + userName + "，修改了文章分类:" + strconv.Itoa(jsonData.ID) + "的内容"
		models.LogAdd(3, "修改文章分类", userId, logData, bid, jsonData.Aid)
	} else {
		var data models.MArticleCategory
		data.Name = jsonData.Name
		data.SubName = jsonData.SubName
		data.Pic = jsonData.Pic
		data.Status = jsonData.Status
		data.Aid = jsonData.Aid
		data.Pid = jsonData.Pid
		data.Bid = jsonData.Bid
		data.Createtime = int(time.Now().Unix())
		err = models.DB.Model(new(models.MArticleCategory)).Create(&data).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 10001,
				"msg":  err.Error(),
			})
			return
		}
		//写入日志
		userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
		userName, bid := models.UserName(userId)
		logData := "管理员：" + userName + "，新增了一个文章分类:" + jsonData.Name
		models.LogAdd(2, "新增文章分类", userId, logData, bid, jsonData.Aid)
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}

// 删除文章分类
func ArticleCateGoryDel(c *gin.Context) {
	var jsonData models.MArticleCategory
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	var data models.MArticleCategory
	models.DB.Model(new(models.MArticleCategory)).Where("id=?", jsonData.ID).First(&data)
	tx := models.DB.Begin()

	//删除
	err = tx.Delete(&models.MArticleCategory{}, jsonData.ID).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10004,
			"msg":  err.Error(),
		})
		tx.Rollback()
		return
	}
	tx.Commit()

	//写入日志
	userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
	userName, bid := models.UserName(userId)
	logData := "管理员：" + userName + "，删除了一个文章分类:" + data.Name
	models.LogAdd(4, "删除文章分类", userId, logData, bid, jsonData.Aid)
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}

// 分类栏目排序
func ArticleCateGorySort(c *gin.Context) {
	//接收id
	var jsonData models.MArticleCategory
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	var data models.MArticleCategory
	models.DB.Model(new(models.MArticleCategory)).Where("id=?", jsonData.ID).First(&data)
	//修改
	err = models.DB.Model(new(models.MArticleCategory)).Where("id=?", jsonData.ID).Update("sort", jsonData.Sort).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10002,
			"msg":  err.Error(),
		})
		return
	}
	//写入日志
	userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
	userName, bid := models.UserName(userId)
	logData := "管理员：" + userName + "，修改文章分类:" + data.Name + "的排序"
	models.LogAdd(5, "文章分类排序", userId, logData, bid, jsonData.Aid)
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}

type ArticleData struct {
	ID          int    `gorm:"type:int(11); primaryKey" json:"id"`
	Aid         int    `gorm:"type:int(11);" json:"aid"`          //商户id
	Bid         int    `gorm:"type:int(11);" json:"bid"`          //用户id
	Cid         int    `gorm:"type:int(11);" json:"cid"`          //用户id
	Name        string `gorm:"type:varchar(255);" json:"name"`    //标题
	Subname     string `gorm:"type:varchar(255);" json:"subname"` //副标题
	Pic         string `json:"pic"`                               //缩略图
	Author      string `json:"author"`                            //作者
	Content     string `json:"content"`                           //内容
	Readcount   int    `json:"readcount"`                         //阅读量
	Status      int    `json:"status"`                            //状态0不显示1显示
	Sort        int    `json:"sort"`                              //排序 越大越靠前
	Createtime  int    `json:"createtime"`                        //创建时间
	Sendtime    string `json:"sendtime"`                          //发布时间
	Reason      string `json:"reason"`                            //
	CateName    string `json:"cate_name"`
	CateSubname string `json:"cate_subname"`
}

// 获取文章内容
func ArticleList(c *gin.Context) {
	var jsonData ShopJson
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonData, "")
		return
	}
	var list []ArticleData
	var count int64
	if jsonData.Page == 0 {
		jsonData.Page = -1
	}
	if jsonData.Limit == 0 {
		jsonData.Limit = -1
	}
	offsetVal := (jsonData.Page - 1) * jsonData.Limit
	if jsonData.Page == -1 && jsonData.Limit == -1 {
		offsetVal = -1
	}
	selectData := "m_article.id,m_article.bid,m_article.aid,m_article.cid,m_article.name,m_article.subname,m_article.pic,m_article.author,m_article.content" +
		",m_article.readcount,m_article.status,m_article.sort,m_article.createtime,m_article.sendtime,m_article.reason,m_article_category.name as cate_name" +
		",m_article_category.sub_name as cate_subname"
	tx := models.DB.Table("m_article").Select(selectData).Joins("left join m_article_category on m_article_category.id=m_article.cid").Where("m_article.aid=?  AND m_article.name LIKE ?", jsonData.Aid, "%"+jsonData.Name+"%")
	if jsonData.Status < 9 {
		tx = tx.Where("m_article.status=?", jsonData.Status)
	}
	if jsonData.Cid > 0 {

		tx = tx.Where("m_article.cid = ?", jsonData.Cid)
	}
	tx = tx.Count(&count).Limit(jsonData.Limit).Offset(offsetVal).Order("m_article.sort ASC").Find(&list)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10001,
			"msg":  err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data": map[string]interface{}{
			"list":  list,
			"count": count,
		},
	})
}

// 新增/修改文章内容
func ArticleAdd(c *gin.Context) {
	//获取传值
	var jsonData models.MArticle
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	var CidData models.MArticleCategory
	err = models.DB.Model(new(models.MArticleCategory)).Where("id=?", jsonData.Cid).First(&CidData).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10001,
			"msg":  err,
		})
		return
	}
	if jsonData.ID > 0 {
		//修改数据
		var editData = map[string]interface{}{
			"name":      jsonData.Name,
			"pic":       jsonData.Pic,
			"status":    jsonData.Status,
			"cid":       jsonData.Cid,
			"subname":   jsonData.Subname,
			"author":    jsonData.Author,
			"content":   jsonData.Content,
			"readcount": jsonData.Readcount,
			"sendtime":  jsonData.Sendtime,
			"reason":    jsonData.Reason,
			"pcid":      CidData.Pid,
		}
		err = models.DB.Model(new(models.MArticle)).Where("id=?", jsonData.ID).Updates(&editData).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 10003,
				"msg":  err.Error(),
			})
			return
		}
		//写入日志
		userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
		userName, bid := models.UserName(userId)
		logData := "管理员：" + userName + "，修改了文章:" + strconv.Itoa(jsonData.ID) + "的内容"
		models.LogAdd(3, "修改文章内容", userId, logData, bid, jsonData.Aid)
	} else {
		var data models.MArticle
		data.Name = jsonData.Name
		data.Subname = jsonData.Subname
		data.Pic = jsonData.Pic
		data.Status = jsonData.Status
		data.Aid = jsonData.Aid
		data.Cid = jsonData.Cid
		data.Bid = jsonData.Bid
		data.Author = jsonData.Author
		data.Content = jsonData.Content
		data.Sendtime = jsonData.Sendtime
		data.Readcount = jsonData.Readcount
		data.Reason = jsonData.Reason
		data.Createtime = int(time.Now().Unix())
		data.Pcid = CidData.Pid
		err = models.DB.Model(new(models.MArticle)).Create(&data).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 10001,
				"msg":  err.Error(),
			})
			return
		}
		//写入日志
		userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
		userName, bid := models.UserName(userId)
		logData := "管理员：" + userName + "，新增了一个文章:" + jsonData.Name
		models.LogAdd(2, "新增文章", userId, logData, bid, jsonData.Aid)
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}

// 删除文章分类
func ArticleDel(c *gin.Context) {
	var jsonData models.MArticle
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	var data models.MArticle
	models.DB.Model(new(models.MArticle)).Where("id=?", jsonData.ID).First(&data)
	tx := models.DB.Begin()

	//删除
	err = tx.Delete(&models.MArticle{}, jsonData.ID).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10004,
			"msg":  err.Error(),
		})
		tx.Rollback()
		return
	}
	tx.Commit()

	//写入日志
	userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
	userName, bid := models.UserName(userId)
	logData := "管理员：" + userName + "，删除了一个文章:" + data.Name
	models.LogAdd(4, "删除文章", userId, logData, bid, jsonData.Aid)
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}

// 分类栏目排序
func ArticleSort(c *gin.Context) {
	//接收id
	var jsonData models.MArticle
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	var data models.MArticle
	models.DB.Model(new(models.MArticle)).Where("id=?", jsonData.ID).First(&data)
	//修改
	err = models.DB.Model(new(models.MArticle)).Where("id=?", jsonData.ID).Update("sort", jsonData.Sort).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10002,
			"msg":  err.Error(),
		})
		return
	}
	//写入日志
	userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
	userName, bid := models.UserName(userId)
	logData := "管理员：" + userName + "，修改文章:" + data.Name + "的排序"
	models.LogAdd(5, "文章分类", userId, logData, bid, jsonData.Aid)
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}
